package io.github.xbeeant.eoffice.util;

import io.github.xbeeant.core.IdWorker;
import io.github.xbeeant.eoffice.antdesign.LoginResponse;
import io.github.xbeeant.eoffice.model.User;
import io.github.xbeeant.spring.security.LoginUser;
import io.github.xbeeant.spring.security.UserHelper;
import io.github.xbeeant.spring.web.SpringContextProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author xiaobiao
 * @version 2021/6/30
 */
public class SecurityHelper {
    private static final Logger logger = LoggerFactory.getLogger(SecurityHelper.class);

    private static final String ANONYMOUS = "anonymousUser";

    public static LoginResponse antLoginResponse(HttpServletRequest request) {
        Authentication authentication = UserHelper.getCurrentUser();
        return antLoginResponse(authentication, request);
    }

    public static LoginResponse antLoginResponse(Authentication authentication, HttpServletRequest request) {
        if (authentication.getPrincipal().equals(ANONYMOUS)) {
            LoginResponse antLoginResponse = new LoginResponse();
            antLoginResponse.setStatus("error");
            return antLoginResponse;
        }
        LoginResponse antLoginResponse = new LoginResponse();
        antLoginResponse.setStatus("ok");
        antLoginResponse.setCurrentAuthority("user");
        return antLoginResponse;
    }

    public static LoginUser<User> currentUser() {
        Authentication currentUser = UserHelper.getCurrentUser();
        if (currentUser instanceof AnonymousAuthenticationToken) {
            return null;
        }
        LoginUser<User> principal = (LoginUser<User>) currentUser.getPrincipal();
        return principal;
    }

    public static String jwtToken(String sessionId) {
        try {
            return URLEncoder.encode(Base64Helper.base64Encode(sessionId + "#" + IdWorker.getId()),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            return sessionId;
        }
    }

    public static String sessionId(HttpServletRequest request) {
        return request.getSession().getId();
    }

    public static String tokenToUserId(String token) {
        String key = Base64Helper.base64Decode(token);
        logger.info("校验token {} key {}", token, key);
        String sessionId = key.split("#")[0];

        FindByIndexNameSessionRepository sessions = SpringContextProvider.getBean(FindByIndexNameSessionRepository.class);
        Session session = sessions.findById(sessionId);
        if (null == session) {
            return null;
        }
        SecurityContextImpl securityContext = session.getAttribute("SPRING_SECURITY_CONTEXT");
        return ((LoginUser) securityContext.getAuthentication().getPrincipal()).getUserId();
    }
}
